<template>
  <div class="profile-page">
    <div class="profile-container">
      <el-card class="profile-card">
        <template #header>
          <div class="profile-header">
            <h2>个人资料</h2>
          </div>
        </template>

        <div class="profile-content">
          <el-row :gutter="40">
            <el-col :span="8">
              <div class="avatar-section">
                <el-avatar :size="120" :src="userAvatar" class="profile-avatar">
                  {{ authService.user?.name?.charAt(0) || 'U' }}
                </el-avatar>
                <el-button type="primary" plain style="margin-top: 1rem;">
                  更换头像
                </el-button>
              </div>
            </el-col>

            <el-col :span="16">
              <el-form
                ref="profileFormRef"
                :model="profileForm"
                :rules="profileRules"
                label-width="100px"
                class="profile-form"
              >
                <el-form-item label="用户名">
                  <el-input v-model="profileForm.username" disabled />
                  <div class="form-help">用户名创建后不可修改</div>
                </el-form-item>

                <el-form-item label="显示名称" prop="displayName">
                  <el-input v-model="profileForm.displayName" />
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="profileForm.email" />
                  <el-tag v-if="authService.user?.emailVerified" type="success" size="small">
                    已验证
                  </el-tag>
                  <el-button v-else type="text" size="small" @click="sendEmailVerification">
                    验证邮箱
                  </el-button>
                </el-form-item>

                <el-form-item label="手机号码">
                  <el-input v-model="profileForm.phoneNumber" />
                  <el-tag v-if="authService.user?.phoneNumberVerified" type="success" size="small">
                    已验证
                  </el-tag>
                </el-form-item>

                <el-form-item label="部门">
                  <el-input v-model="profileForm.department" />
                </el-form-item>

                <el-form-item label="职位">
                  <el-input v-model="profileForm.position" />
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="updateProfile" :loading="updating">
                    保存更改
                  </el-button>
                  <el-button @click="resetForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <el-card class="security-card">
        <template #header>
          <h3>安全设置</h3>
        </template>

        <div class="security-content">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="security-item">
                <div class="security-info">
                  <h4>修改密码</h4>
                  <p>定期更改密码以提高账户安全性</p>
                </div>
                <el-button type="primary" @click="showChangePasswordDialog">
                  修改密码
                </el-button>
              </div>
            </el-col>

            <el-col :span="12">
              <div class="security-item">
                <div class="security-info">
                  <h4>双因子认证</h4>
                  <p>启用双因子认证以增强安全性</p>
                </div>
                <el-button :type="mfaEnabled ? 'success' : 'warning'" @click="configureMFA">
                  {{ mfaEnabled ? '已启用' : '启用 MFA' }}
                </el-button>
              </div>
            </el-col>
          </el-row>

          <el-divider />

          <div class="login-history">
            <h4>登录历史</h4>
            <el-table :data="loginHistory" style="width: 100%">
              <el-table-column prop="loginTime" label="登录时间" width="180" />
              <el-table-column prop="ipAddress" label="IP地址" width="140" />
              <el-table-column prop="location" label="位置" />
              <el-table-column prop="device" label="设备" />
              <el-table-column prop="status" label="状态" width="80">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'success' ? 'success' : 'danger'" size="small">
                    {{ row.status === 'success' ? '成功' : '失败' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="changePasswordVisible" title="修改密码" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef">
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="changePasswordVisible = false">取消</el-button>
        <el-button type="primary" @click="changePassword" :loading="changingPassword">
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import authService from '@/services/AuthService'

interface LoginHistory {
  loginTime: string
  ipAddress: string
  location: string
  device: string
  status: 'success' | 'failed'
}

const updating = ref(false)
const changingPassword = ref(false)
const changePasswordVisible = ref(false)
const mfaEnabled = ref(false)

const profileForm = reactive({
  username: '',
  displayName: '',
  email: '',
  phoneNumber: '',
  department: '',
  position: ''
})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const loginHistory = ref<LoginHistory[]>([
  {
    loginTime: '2024-10-26 18:30:15',
    ipAddress: '192.168.1.100',
    location: '北京',
    device: 'Chrome / Windows',
    status: 'success'
  },
  {
    loginTime: '2024-10-26 09:15:22',
    ipAddress: '192.168.1.100',
    location: '北京',
    device: 'Chrome / Windows',
    status: 'success'
  }
])

const userAvatar = computed(() => {
  return authService.user?.avatar || ''
})

const profileRules = {
  displayName: [
    { required: true, message: '请输入显示名称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码至少需要8个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

onMounted(() => {
  loadUserProfile()
})

const loadUserProfile = () => {
  const user = authService.user
  if (user) {
    profileForm.username = user.username || ''
    profileForm.displayName = user.displayName || user.name || ''
    profileForm.email = user.email || ''
    profileForm.phoneNumber = user.phoneNumber || ''
    profileForm.department = '技术部' // 模拟数据
    profileForm.position = '系统管理员' // 模拟数据
  }
}

const updateProfile = async () => {
  try {
    updating.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 更新本地用户信息
    if (authService.user) {
      authService.user.displayName = profileForm.displayName
      authService.user.email = profileForm.email
    }

    ElMessage.success('个人资料更新成功')
  } catch (error) {
    ElMessage.error('更新失败，请稍后重试')
  } finally {
    updating.value = false
  }
}

const resetForm = () => {
  loadUserProfile()
}

const sendEmailVerification = async () => {
  try {
    // 模拟发送验证邮件
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('验证邮件已发送，请查收')
  } catch (error) {
    ElMessage.error('发送验证邮件失败')
  }
}

const showChangePasswordDialog = () => {
  // 重置表单
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  changePasswordVisible.value = true
}

const changePassword = async () => {
  try {
    changingPassword.value = true

    // 模拟密码修改API调用
    await new Promise(resolve => setTimeout(resolve, 1500))

    ElMessage.success('密码修改成功，请重新登录')
    changePasswordVisible.value = false

    // 登出用户
    await authService.logout()
    // 跳转到登录页
    window.location.href = '/login'
  } catch (error) {
    ElMessage.error('密码修改失败')
  } finally {
    changingPassword.value = false
  }
}

const configureMFA = () => {
  if (mfaEnabled.value) {
    ElMessage.info('禁用双因子认证功能开发中...')
  } else {
    ElMessage.info('启用双因子认证功能开发中...')
  }
}
</script>

<style scoped>
.profile-page {
  padding: 2rem;
  background: #f5f7fa;
  min-height: 100vh;
}

.profile-container {
  max-width: 1200px;
  margin: 0 auto;
}

.profile-card,
.security-card {
  margin-bottom: 2rem;
}

.profile-header h2 {
  margin: 0;
  color: #333;
}

.profile-content {
  padding: 1rem 0;
}

.avatar-section {
  text-align: center;
}

.profile-avatar {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  font-size: 3rem;
  font-weight: bold;
  margin-bottom: 1rem;
}

.form-help {
  font-size: 0.8rem;
  color: #999;
  margin-top: 0.25rem;
}

.security-content h3 {
  margin: 0 0 1rem 0;
  color: #333;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  margin-bottom: 1rem;
}

.security-info h4 {
  margin: 0 0 0.5rem 0;
  color: #333;
}

.security-info p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

.login-history {
  margin-top: 2rem;
}

.login-history h4 {
  margin: 0 0 1rem 0;
  color: #333;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-page {
    padding: 1rem;
  }

  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
}
</style>